import validate from '@/utils/validate'
import { parseTime } from '@/utils/index'

var search = {
  v: '1.0.0'

  /**
   * 列表搜索参数
   */
  , queryParams: {
    'filters': {}
    , 'page': 1
    , 'pageSize': 10
    , 'sort': []
    , 'fields': ['*']
  }

  /**
   * 获取搜索条件
   */
  , searchFliters: function(searchFields, query) {
    let complexSearch
    const filters = []
    const baseSearch = this.baseFliters(searchFields, query.searchText)
    if (validate.notEmpty(baseSearch)) {
      filters.push(baseSearch)
    }

    if (validate.notEmpty(complexSearch = (query.isComplex ? this.complexFliters(searchFields, query.whereFields) : null))) {
      filters.push(complexSearch)
    }

    return validate.isEmpty(filters) ? {} : {
      filters: filters
      , operator: 'and'
    }
  }

  /**
   * 获取基础自由搜索
   */
  , baseFliters: function(searchFields, searchText) {
    const filters = []
    searchText = validate.notEmpty(searchText) ? searchText.trim() : searchText
    if (validate.notEmpty(searchText) && validate.notEmpty(searchFields)) {
      for (var field of searchFields) {
        const filter = Object.prototype.hasOwnProperty.call(field, 'name') && Object.prototype.hasOwnProperty.call(field, 'type') ? this.baseFieldFilter(field, searchText) : null
        if (validate.notEmpty(filter)) {
          filters.push(filter)
        }
      }
    }

    return validate.isEmpty(filters) ? {} : {
      filters: filters
      , operator: 'or'
    }
  }

  /**
   * 获取高级搜索
   */
  , complexFliters: function(searchFields, whereFields) {
    const filters = []
    // 过滤掉没用字段
    searchFields = searchFields.filter(field => Object.prototype.hasOwnProperty.call(field, 'name') && Object.prototype.hasOwnProperty.call(field, 'type') && Object.prototype.hasOwnProperty.call(whereFields, field.name))
    if (validate.notEmpty(searchFields)) {
      for (var field of searchFields) {
        let searchText = whereFields[field.name]
        if (typeof (searchText) === 'undefined' && searchText !== 0) {
          continue
        }

        searchText = validate.isString(searchText) ? searchText.trim() : searchText
        const filter = this.complexFieldFilter(field, searchText)
        if (validate.notEmpty(filter)) {
          filters.push(filter)
        }
      }
    }

    return validate.isEmpty(filters) ? {} : {
      filters: filters
      , operator: 'and'
    }
  }

  /**
   * 基础自由搜索条件处理
   */
  , baseFieldFilter: function(field, value) {
    let isEmpty = true
    let type = field.type.toLowerCase()
    const filter = {
      field: field.name
      , operator: 'like'
      , value: value
    }

    if (field.selection) {
      type = 'selection'
    }

    switch (type) {
      case 'selection':
        var selectionIteam = field.selectionList.find(v => v.label.toLowerCase() === value.toLowerCase())
        if (validate.notEmpty(selectionIteam)) {
          isEmpty = false
          filter.operator = '='
          filter.value = selectionIteam.value
        }
        break

      case 'long':
        if (validate.validIntNum(value)) {
          isEmpty = false
          filter.operator = '='
        }
        break

      case 'integer':
        if (validate.validInteger(value)) {
          isEmpty = false
          filter.operator = '='
        }
        break

      case 'float':
      case 'decimal':
        if (validate.validNumber(value)) {
          isEmpty = false
          filter.operator = '='
        }
        break

      case 'text':
      case 'string':
        isEmpty = false
        break

      case 'boolean':
        if (validate.validBoolean(value)) {
          isEmpty = false
          filter.operator = '='
          filter.value = validate.validBoolTrue(value)
        }
        break
    }

    return isEmpty ? {} : filter
  }

  /**
   * 高级搜索条件处理
   */
  , complexFieldFilter: function(field, value) {
    let isEmpty = true
    let type = field.type.toLowerCase()
    const filter = {
      field: field.name
      , operator: 'like'
      , value: value
    }

    if (field.selection) {
      type = 'selection'
    }

    if ((type !== 'selection' && validate.isEmpty(value)) || (['date', 'datetime'].indexOf(type) !== -1 && !validate.isDate(value[0]))) {
      return null
    }

    switch (type) {
      case 'selection':
      case 'integer':
      case 'long':
      case 'float':
      case 'decimal':
        isEmpty = false
        filter.operator = '='
        break

      case 'text':
      case 'string':
        isEmpty = false
        break

      case 'boolean':
        isEmpty = false
        filter.operator = '='
        filter.value = validate.validBoolTrue(value)
        break

      case 'date':
        var dateFormat = '{y}-{m}-{d}'
        isEmpty = false
        filter.operator = 'between'
        filter.value = parseTime(value[0], dateFormat)
        filter.value1 = parseTime(value[1], dateFormat)
        if (filter.value === filter.value1) {
          filter.operator = '='
          delete filter.value1
        }
        break

      case 'datetime':
        isEmpty = false
        filter.operator = 'between'
        filter.value = parseTime(value[0])
        filter.value1 = new Date(value[1].setDate(value[1].getDate() + 1))
        filter.value1 = parseTime(filter.value1.setTime(filter.value1.getTime() - 1000))
        break
    }

    return isEmpty ? {} : filter
  }

  /**
   * 处理表格排序
   */
  , handleTableSort: function(val) {
    if (validate.isEmpty(val) || validate.isEmpty(val.order)) {
      return []
    }

    return [val.order === 'descending' ? '-' + val.prop : val.prop]
  }

  /**
   * 获取列表参数
   */
  , getQueryParams: function(othis) {
    this.queryParams.filters = this.searchFliters(othis.searchFields, othis.filters)
    this.queryParams.page = validate.isEmpty(othis.currentPage) ? this.queryParams.page : othis.currentPage
    this.queryParams.fields = validate.isEmpty(othis.fields) ? this.queryParams.fields : othis.fields
    this.queryParams.pageSize = validate.isEmpty(othis.pageSize) ? this.queryParams.pageSize : othis.pageSize
    this.queryParams.sort = validate.isEmpty(othis.sort) ? this.queryParams.sort : this.handleTableSort(othis.sort)
    return this.queryParams
  }
}

export default search
